package service

import (
	"Data-API-MCP/backend/internal/domain/entity"
	"Data-API-MCP/backend/internal/domain/repository"
	"context"
	"time"
)

// APICallService API调用记录服务接口
type APICallService struct {
	callRepo repository.APICallRepository
}

// NewAPICallService 创建API调用记录服务实例
func NewAPICallService(callRepo repository.APICallRepository) *APICallService {
	return &APICallService{
		callRepo: callRepo,
	}
}

// CreateCall 创建API调用记录
func (s *APICallService) CreateCall(ctx context.Context, call *entity.APICall) error {
	call.CreatedAt = time.Now()
	call.UpdatedAt = time.Now()
	return s.callRepo.Create(ctx, call)
}

// GetCall 获取API调用记录
func (s *APICallService) GetCall(ctx context.Context, id string) (*entity.APICall, error) {
	return s.callRepo.FindByID(ctx, id)
}

// ListCalls 获取API调用记录列表
func (s *APICallService) ListCalls(ctx context.Context, offset, limit int) ([]*entity.APICall, error) {
	return s.callRepo.List(ctx, offset, limit)
}

// ListCallsByAPI 获取指定API的调用记录列表
func (s *APICallService) ListCallsByAPI(ctx context.Context, apiID string, offset, limit int) ([]*entity.APICall, error) {
	return s.callRepo.ListByAPIID(ctx, apiID, offset, limit)
}

// ListCallsByTimeRange 获取指定时间范围内的调用记录列表
func (s *APICallService) ListCallsByTimeRange(ctx context.Context, startTime, endTime time.Time, offset, limit int) ([]*entity.APICall, error) {
	return s.callRepo.ListByTimeRange(ctx, startTime, endTime, offset, limit)
}

// ListCallsByCaller 获取指定调用者的调用记录列表
func (s *APICallService) ListCallsByCaller(ctx context.Context, caller string, offset, limit int) ([]*entity.APICall, error) {
	return s.callRepo.ListByCaller(ctx, caller, offset, limit)
}

// GetCallCount 获取调用记录总数
func (s *APICallService) GetCallCount(ctx context.Context) (int64, error) {
	return s.callRepo.Count(ctx)
}

// GetCallCountByAPI 获取指定API的调用记录总数
func (s *APICallService) GetCallCountByAPI(ctx context.Context, apiID string) (int64, error) {
	return s.callRepo.CountByAPIID(ctx, apiID)
}

// GetCallCountByTimeRange 获取指定时间范围内的调用记录总数
func (s *APICallService) GetCallCountByTimeRange(ctx context.Context, startTime, endTime time.Time) (int64, error) {
	return s.callRepo.CountByTimeRange(ctx, startTime, endTime)
}

// GetCallCountByCaller 获取指定调用者的调用记录总数
func (s *APICallService) GetCallCountByCaller(ctx context.Context, caller string) (int64, error) {
	return s.callRepo.CountByCaller(ctx, caller)
}

// GetStatistics 获取API调用统计信息
func (s *APICallService) GetStatistics(ctx context.Context, apiID string, startTime, endTime time.Time) (*entity.APIStatistics, error) {
	return s.callRepo.GetStatistics(ctx, apiID, startTime, endTime)
}
